﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Configuration;
using EmoneyWeiXinEntity;
using System.Data;
using System.IO;
using System.Xml;
using System.Web.Mvc;

namespace EmoneyWeiXinCommon
{
    public class StringTools
    {
        public static void GetSendMail(string content)
        {
            try
            {
                SendMail semail = new SendMail();
                semail.MailTo = Config.MailUsername.Split('|');
                semail.Subject = "EmoneyWeiXin项目程序";
                semail.Body = content;
                semail.Send();
            }
            catch (Exception ex)
            {
                
            }
        }


        /// <summary>
        /// 获取静态文件地址
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetStaticFile(string file)
        {
            var str = Config.StaticFile;
            if (str == "~/")
            {
                UrlHelper he = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                string path = he.Content("~/" + file);
                return path;
            }
            else
            {
                return str + file;
            }
        }

        public static string GetTrendsFile(string file)
        {
            UrlHelper he = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
            return he.Content("~/" + file);
        }

        //创建随机字符串  
        public static string createNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            Random rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        public static string ChangeRealKey(string key, string code)
        {
            try
            {
                switch (key)
                {
                    case "memu":
                        return "EmoneyWeiXinCommon." + key + code;
                    case "weixinUser":
                        return "EmoneyWeiXinCommon." + key + code;
                    case "newsreport":
                        return "EmoneyWeiXinCommon." + key + code;
                    case "reply":
                        return "EmoneyWeiXinCommon." + key + code;
                    case "replyReports":
                        return "EmoneyWeiXinCommon." + key + code;

                    default:
                        return "EmoneyWeiXinCommon." + key + code;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static string getWeekday(DateTime dtime)
        {
            string dt = dtime.DayOfWeek.ToString();
            string week = "";
            switch (dt)
            {
                case "Monday":
                    week = "1";
                    break;
                case "Tuesday":
                    week = "2";
                    break;
                case "Wednesday":
                    week = "3";
                    break;
                case "Thursday":
                    week = "4";
                    break;
                case "Friday":
                    week = "5";
                    break;
                case "Saturday":
                    week = "6";
                    break;
                case "Sunday":
                    week = "7";
                    break;
            }
            return week;
        }

        public static String GetShaEntity(String str)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[] 
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash;
        }

        //SHA1哈希加密算法  
        public string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out).Replace("-", "").ToLower();
            return str_sha1_out;
        }



        /// <summary>  
        /// datetime转换为unixtime  
        /// </summary>  
        /// <param name="time"></param>  
        /// <returns></returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d">double 型数字</param>
        /// <returns>DateTime</returns>
        public static System.DateTime ConvertIntDateTime(int d)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return startTime.AddSeconds(d);
        }


        /// <summary>
        /// 查看是否是数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool isNumberic5(string str)
        {
            return !string.IsNullOrEmpty(str) && Regex.IsMatch(str, "^\\d+$");
        }


        public static void CreateFile(string filename)
        {
            if (System.IO.Directory.Exists(filename) == false)//如果不存在就创建file文件夹 
            {
                System.IO.Directory.CreateDirectory(filename);
            }
        }


        public static string keyIniname = "WeixinManagerCommon"; //配置文件用

        public static string GetListSelect(string TableKey)
        {
            string filename = Config.ConfigPath + "config.ini";

            INIClass ini = new INIClass(filename);

            return ini.IniReadValue(keyIniname, TableKey);
        }

        public static bool GetListUpdate(string TableKey, string updatetime)
        {
            try
            {
                CreateFile(Config.ConfigPath);
                if (string.IsNullOrEmpty(updatetime))
                {
                    return true;
                }
                string filename = Config.ConfigPath + "config.ini";

                INIClass ini = new INIClass(filename);

                string value = ini.IniReadValue(keyIniname, TableKey);
                if (value == "")
                {
                    ini.IniWriteValue(keyIniname, TableKey, updatetime);
                    return true;
                }
                else
                {
                    if (value == updatetime)
                    {
                        return false;
                    }
                    else
                    {
                        ini.IniWriteValue(keyIniname, TableKey, updatetime);
                        return true;
                    }
                }

            }
            catch (Exception)
            {
            }
            return false;
        }

        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="filename"></param>
        /// <param name="data"></param>
        /// <returns></returns>

        public static UploadResult UploadFile(string path, string filename, byte[] data)
        {
            string fileuploadUrl = ConfigurationManager.AppSettings["FileuploadUrl"].ToString();
            HttpUploadFile u = new HttpUploadFile();
            string ss = u.UploadFile(fileuploadUrl, path, filename, data);
            UploadResult obj = new UploadResult();
            if (!string.IsNullOrEmpty(ss))
                obj = JsonConvert.DeserializeObject<UploadResult>(ss);
            return obj;
        }

        public static string GetNumberTostr(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = Regex.Replace(str, @"[^\d.\d]", "");
                return str;
            }
            else
            {
                return "";
            }
        }

        public static string CapCode(Match m)
        {
            if (m.ToString() != "")
            {
                return "<spc>" + m.ToString() + "</spc>";
            }
            return "";
        }

        /// <summary>
        /// 获取汉字首字母（可包含多个汉字）
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string GetChineseSpell(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += getSpell(strText.Substring(i, 1)).ToLower();
            }
            return myStr;
        }

        public static string getSpell(string cnChar)
        {
            byte[] arrCN = Encoding.Default.GetBytes(cnChar);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "*";
            }
            else
                return cnChar;
        }

        public static bool IsNumber(string TextValue)
        {
            try
            {
                int n = Convert.ToInt32(TextValue.Trim());
                return true;
            }
            catch
            {
                return false;
            }
        }

        //去掉字符串中的非安全字符，防止sql注入
        public static string Text2SafeSql(string text)
        {
            return text.Replace("'", "").Replace("--", "").ToUpper().Replace("UPDATE", "").Replace("DELETE", "");
        }

        public static string GetXml(string strxml, string weixinid, string updatetime, object Content)
        {
            StringBuilder stb = new StringBuilder();
            if (!string.IsNullOrEmpty(strxml))
            {
                strxml = strxml.Replace("同步2", "");
                if (!string.IsNullOrEmpty(strxml))
                {
                    MemcachedTools1 mmtools = new MemcachedTools1();

                    string keys = StringTools.ChangeRealKey("weixinUser", weixinid);
                    var obj = mmtools.Get(keys);
                    weixinUserEntity objwexinuser = new weixinUserEntity();
                    if (obj != null)
                    {
                        objwexinuser = JsonTools.ToObject<weixinUserEntity>(obj.ToString());
                    }

                    string nickname = "";
                    if (objwexinuser != null)
                    {
                        nickname = objwexinuser.title;
                    }
                    string[] strArr = Regex.Split(strxml, @"\^{3}");
                    for (int i = strArr.Length - 1; i >= 0; i--)
                    {
                        if (!string.IsNullOrEmpty(strArr[i]))
                        {
                            if (strArr[i].Contains("<xml>"))
                            {
                                DataSet ds = new DataSet();
                                //读取字符串中的信息  
                                StringReader StrStream = new StringReader(strArr[i]);
                                //获取StrStream中的数据  
                                XmlTextReader Xmlrdr = new XmlTextReader(StrStream);
                                ds.ReadXml(Xmlrdr);

                                if (ds != null && ds.Tables.Count > 0)
                                {
                                    if (ds.Tables["xml"] != null && ds.Tables["xml"].Rows.Count > 0)
                                    {
                                        string MsgType = ds.Tables["xml"].Rows[0]["MsgType"].ToString();
                                        if (MsgType == "news")
                                        {
                                            stb.Append("<li>");
                                            stb.Append("<span class=\"manage_batch_left manage_batch_left02\">");
                                            stb.Append("<input type=\"checkbox\"></span>");
                                            stb.Append("<div class=\"manage_batch_center\">");
                                            stb.Append("<dl>");
                                            stb.Append("<dt><a href=\"javascript:void(0);\">");
                                            stb.Append("<img src=\"http://emhg.emoney.cn/Static/upload/default.png\"></a></dt>");
                                            stb.Append("<dd>");
                                            stb.Append("<h4>");
                                            stb.Append("<span>" + nickname + "</span>");
                                            stb.Append("<span style=\"margin-left:208px;\">" + updatetime + "</span></h4>");
                                            stb.Append("<p>[图文消息]" + ds.Tables["item"].Rows[0]["Title"].ToString() + "</p><p>" + ds.Tables["item"].Rows[0]["Description"].ToString() + "</p>" + "</p>");
                                            stb.Append("</dd>");
                                            stb.Append(" </dl>");
                                            stb.Append("</div>");

                                            stb.Append("</li>");
                                        }
                                        else if (MsgType == "text")
                                        {
                                            stb.Append("<li>");
                                            stb.Append("<span class=\"manage_batch_left manage_batch_left02\">");
                                            stb.Append("<input type=\"checkbox\"></span>");
                                            stb.Append("<div class=\"manage_batch_center\">");
                                            stb.Append("<dl>");
                                            stb.Append("<dt><a href=\"javascript:void(0);\">");
                                            stb.Append("<img src=\"http://emhg.emoney.cn/Static/upload/default.png\"></a></dt>");
                                            stb.Append("<dd>");
                                            stb.Append("<h4>");
                                            stb.Append("<span>" + nickname + "</span>");
                                            stb.Append("<span style=\"margin-left:208px;\">" + updatetime + "</span></h4>");
                                            stb.Append("<p>[文本消息]" + ds.Tables[0].Rows[0]["Content"].ToString() + "</p>");
                                            stb.Append("</dd>");
                                            stb.Append(" </dl>");
                                            stb.Append("</div>");

                                            stb.Append("</li>");

                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (IsNumber(strArr[i]) || strArr[i].Contains("^"))
                                {
                                    string[] strBcrr = strArr[i].Split('^');
                                    string TitleName = "[" + (strBcrr.Length - 1 > 1 ? "多" : "") + "图文消息]";
                                    for (int kq = 0; kq < strBcrr.Length; kq++)
                                    {
                                        keys = ChangeRealKey("newsreport", weixinid + strBcrr[kq].Trim());
                                        var objkeys = mmtools.Get(keys);
                                        if (objkeys != null)
                                        {
                                            NewsReportEntity newsreport = JsonTools.ToObject<NewsReportEntity>(objkeys.ToString());
                                            if (newsreport != null && newsreport.ID > 0)
                                            {
                                                TitleName += "<p>(图文" + (kq + 1) + ")" + newsreport.title + "</p><p>" + newsreport.Summary + "</p>";
                                            }
                                        }

                                    }

                                    stb.Append("<li>");
                                    stb.Append("<span class=\"manage_batch_left manage_batch_left02\">");
                                    stb.Append("<input type=\"checkbox\"></span>");
                                    stb.Append("<div class=\"manage_batch_center\">");
                                    stb.Append("<dl>");
                                    stb.Append("<dt><a href=\"javascript:void(0);\">");
                                    stb.Append("<img src=\"http://emhg.emoney.cn/Static/upload/default.png\"></a></dt>");
                                    stb.Append("<dd>");
                                    stb.Append("<h4>");
                                    stb.Append("<span>" + nickname + "</span>");
                                    stb.Append("<span style=\"margin-left:208px;\">" + updatetime + "</span></h4>");
                                    stb.Append("<p>" + TitleName + "</p>");
                                    stb.Append("</dd>");
                                    stb.Append(" </dl>");
                                    stb.Append("</div>");

                                    stb.Append("</li>");
                                }
                                else
                                {
                                    stb.Append("<li>");
                                    stb.Append("<span class=\"manage_batch_left manage_batch_left02\">");
                                    stb.Append("<input type=\"checkbox\"></span>");
                                    stb.Append("<div class=\"manage_batch_center\">");
                                    stb.Append("<dl>");
                                    stb.Append("<dt><a href=\"javascript:void(0);\">");
                                    stb.Append("<img src=\"http://emhg.emoney.cn/Static/upload/default.png\"></a></dt>");
                                    stb.Append("<dd>");
                                    stb.Append("<h4>");
                                    stb.Append("<span>" + nickname + "</span>");
                                    stb.Append("<span style=\"margin-left:208px;\">" + updatetime + "</span></h4>");

                                    if (Content != null && Content.ToString() == "voice")
                                    {
                                        stb.Append("<p>[语音消息]" + strArr[i] + "</p>");
                                    }
                                    else
                                    {
                                        stb.Append("<p>[文本消息]" + strArr[i] + "</p>");
                                    }

                                    stb.Append("</dd>");
                                    stb.Append(" </dl>");
                                    stb.Append("</div>");

                                    stb.Append("</li>");
                                }
                            }
                        }
                    }
                }
            }
            return stb.ToString();
        }

        public static string Md5(String s)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
            bytes = md5.ComputeHash(bytes);
            md5.Clear();

            string ret = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
            }

            return ret.PadLeft(32, '0');
        }
        /// <summary>
        /// 将手机号码中间4位换成*号
        /// </summary>
        /// <returns></returns>
        public static string HideMobilePhoneMid4(string phone)
        {
            string result = "";
            for (int i = 0; i < phone.Length; i++)
            {
                if (i > 2 && i < 7)
                {
                    result += "*";
                }
                else
                {
                    result += phone[i];
                }
            }
            return result;
        }




        //发送文本的json
        public static string GetSendWbJson(string str)
        {
            string strContext = "";
            strContext += "{";
            strContext += "\"touser\":\"{0}\",";
            strContext += "\"msgtype\":\"text\",";
            strContext += "\"text\":";
            strContext += "{";
            strContext += "\"content\":\"" + str + "\"";
            strContext += "}}";
            return strContext;
        }


        /// <summary>
        /// 发送图文信息的拼接方法
        /// </summary>
        /// <param name="newsr"></param>
        /// <returns></returns>
        public static string GetNewsPortJson(List<NewsReportEntity> Listnewsr)
        {
            string strContext = "";
            strContext += "{";
            strContext += "\"touser\":\"{0}\",";
            strContext += "\"msgtype\":\"news\",";
            strContext += "\"news\":{";
            strContext += "\"articles\": [";

            for (int i = 0; i < Listnewsr.Count; i++)
            {
                strContext += "{";
                strContext += "\"title\":\"" + Listnewsr[i].title + "\",";
                strContext += "\"description\":\"" + Listnewsr[i].Summary + "\",";
                if (!string.IsNullOrEmpty(Listnewsr[i].OutsideUrl))
                {
                    if (Listnewsr[i].OutsideUrl.Contains("?"))
                    {
                        strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "&fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                    }
                    else
                    {
                        strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                    }
                }
                else
                {
                    strContext += "\"url\":\"" + Config.selNewsReportUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                }
                strContext += "\"picurl\":\"" + Listnewsr[i].ImageUrl + "\"";
                strContext += "}";

                if (i != Listnewsr.Count - 1)
                {
                    strContext += ",";
                }
            }
            strContext += "]";
            strContext += "}";
            strContext += "}";
            return strContext;
        }



        public static string RemoveHtmlTarget(string html)
        {
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记 
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 网管网bitsCN.com 
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 
            html = regex4.Replace(html, ""); //过滤iframe 
            html = regex5.Replace(html, ""); //过滤frameset 
            html = regex6.Replace(html, ""); //过滤frameset 
            html = regex7.Replace(html, ""); //过滤frameset 
            html = regex8.Replace(html, ""); //过滤frameset 
            html = regex9.Replace(html, "");
            html = html.Replace(" ", "");


            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            return html;
        }
    }






}
